package com.download.backstage.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.download.util.UploadUtil;
import com.download.web.entity.BusArticleLable;
import com.download.web.entity.model.ArticleListModel;
import com.download.web.entity.model.ArticleModel;
import com.download.web.entity.model.Page;
import com.download.web.entity.model.Result;
import com.download.web.mapper.BusArticleMapper;
import com.download.web.service.IBusArticleLableService;
import com.download.web.service.IBusArticleService;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author cmy
 * @since 2019-02-20
 */
@Controller
@RequestMapping("/backstage/article")
public class BackArticleController {

    @Autowired
    private IBusArticleService articleService;

    @Autowired
    private IBusArticleLableService articleLableService;

    @Value("${upload.image.src}")
    private String src;
    @Value("${upload.image.url}")
    private String url;


    @ResponseBody
    @RequestMapping("/selectArticlesByType")
    public Page<ArticleListModel> selectArticlesByType(@RequestParam(name = "pageIndex",defaultValue = "1") Integer pageIndex, @RequestParam(name = "pageSize",defaultValue = "10")Integer pageSize,
                                                       Integer type,String keywords) {
        Page<ArticleListModel> articles = articleService.articlePageByTypeAndKeywords(keywords,pageIndex, pageSize, type);
        return articles;
    }


    /**
     * 新增文章
     *
     * @param articleModel
     */
    @ResponseBody
    @RequestMapping("/saveArticle")
    public String saveArticle(@RequestBody @Valid ArticleModel articleModel, BindingResult bindingResult) {
        //todo 文章图片关联保存
        if (bindingResult.hasErrors()) {
            return bindingResult.getFieldErrors().get(0).getDefaultMessage();
        }
        articleService.saveArticle(articleModel);
        return "ok";
    }

    /**
     * 删除文章
     *
     * @param id
     */
    @ResponseBody
    @RequestMapping("/delArticleById")
    public void delArticleById(Integer id) {
        articleService.removeById(id);
        articleLableService.remove(new QueryWrapper<BusArticleLable>().eq("article_id",id));
    }

    /**
     * 修改文章
     *
     * @param articleModel
     */
    @ResponseBody
    @RequestMapping("/updateArticle")
    public String updateArticle(@RequestBody @Valid ArticleModel articleModel, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return bindingResult.getFieldErrors().get(0).getDefaultMessage();
        }
        articleService.updateArticle(articleModel);
        return "ok";
    }

    /**
     * 按文章id查找文章信息
     *
     * @param id
     */
    @ResponseBody
    @RequestMapping("/findArticleById")
    public ArticleModel findArticleById(@RequestParam("id") Integer id) {
        ArticleModel articleModel = articleService.findArticleById(id);
        return articleModel;
    }


    @ResponseBody
    @RequestMapping("/uploadImage")
    public Result uploadImage(@RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request, HttpServletResponse response) throws IOException {
        Result result = new Result();
       /* String contentType = file.getContentType();   //图片文件类型
        String fileName = file.getOriginalFilename();  //图片名字
        //文件存放路径
        String filePath = request.getSession().getServletContext().getRealPath("/static/upload/article/");
//        String filePath = "C:\\Users\\Administrator\\Desktop\\vue-manage-system-master\\static\\uploadimg\\";
        File targetFile = new File(filePath);
        if (!targetFile.exists()) {
            targetFile.mkdirs();
        }
        String fileUrl = filePath ;
        String uploadFileName= new Date().getTime() +"-" + fileName;
        FileOutputStream out = new FileOutputStream(fileUrl+uploadFileName);
        out.write(file.getBytes());
        out.flush();
        out.close();*/

        String path=UploadUtil.upload(src,file);

        result.setCode(0);
        result.setMsg("图片上传成功");
        Map<String, Object> map = new HashMap<>();
//        map.put("url", "/static/upload/article/"+uploadFileName);
//        map.put("src",url+path);
        map.put("src",url+path);
        result.setData(map);


        return result;
    }

    @RequestMapping("/historicalVersion")
    public ModelAndView historicalVersion(Integer artId){
        ModelAndView mv=new ModelAndView("backstage/historicalversion");
        mv.addObject("artId",artId);
        return mv;
    }
}
